﻿using System.Diagnostics;
using System.Management;
using System.Net.NetworkInformation;

namespace Roovent.Network
{
	static public class NetworkTool
	{
		/// <summary>
		/// 判断是否有活跃的物理网卡
		/// </summary>
		/// <returns>True:有/False:没有</returns>
		static public bool GetIsNetworkAdapterAvailable()
		{
			/*	NetConnetcionStatus
			 *		0 (0x0) Disconnected
			 *		1 (0x1) Connecting
			 *		2 (0x2) Connected
			 *		3 (0x3) Disconnecting
			 *		4 (0x4) Hardware not present
			 *		5 (0x5) Hardware disabled
			 *		6 (0x6) Hardware malfunction
			 *		7 (0x7) Media disconnected
			 *		8 (0x8) Authenticating
			 *		9 (0x9) Authentication succeeded
			 *		10 (0xA) Authentication failed
			 *		11 (0xB) Invalid address
			 *		12 (0xC) Credentials required
			 *	
			 *	PNPDeviceID
			 *		Windows Plug and Play device identifier of the logical device.
			 *		如果前面有 PCI 就是本机的真实网卡 
			 */
			ManagementObjectSearcher s = new ManagementObjectSearcher(
				@"SELECT DeviceID FROM Win32_NetworkAdapter WHERE NetConnectionStatus=2 AND PNPDeviceID LIKE 'PCI%'"); //
			return s.Get().Count > 0;
		}

		static private Ping p = new Ping();
		static private string[] destIP = { "www.baidu.com", "www.qq.com", "www.sina.com" };

		/// <summary>
		/// 判断是否连接上互联网
		/// </summary>
		/// <returns>True:已连接/False:未连接</returns>
		static public bool GetIsConnectedToInternet()
		{
			for (int i = 0; i < destIP.Length; ++i)
			{
				try
				{
					PingReply pr = p.Send(destIP[i], 1000);
					Debug.WriteLine(string.Format("{0}:{1} {2} {3}", i.ToString(), destIP[i], pr.Status, pr.RoundtripTime));

					if (pr.Status == IPStatus.Success)
					{
						return true;
					}
					if (pr.Status == IPStatus.HardwareError)
					{
						break;
					}
				}
				catch (PingException)
				{
					break;
				}
			}
			return false;
		}
	}
}
